﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScannerApp.Common
{
   public class Authorize
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Tuple<string,int,string> CheckAuth() {

            try
            {
                string licPath = AppDomain.CurrentDomain.BaseDirectory + @"WinProLic.lic";
                string lic = JsonHelper.ReadJson(licPath);
                string s = cryptHelper.Decrypt(lic);
                LicEntity l = JsonHelper.ToObject<LicEntity>(s);
                int licdate=   DateDiff(DateTime.Now, l.AuDate);
                int ErrorTime = l.ErrorTime;
                int errorcode = 0;
                string erromsg = "";
                if (l.IsFirst == "N") {
                    if (ErrorTime >= 3) {
                        erromsg = "错误:你已经修改本地时间三次,请联系供应商重新许可!";
                        licdate = l.LicDate;
                        errorcode =-997;
                    }
                    if (l.LicDate < licdate)
                    {
                        ErrorTime = ErrorTime + 1;
                        erromsg = "错误:请勿修改本地时间,三次以后许可自动失效!";
                        licdate = l.LicDate;
                        errorcode =-998;
                    }
                }
                object o = new
                {
                    Company = l.Company,
                    AuDate = l.AuDate,
                    IsFirst = "N",
                    LicDate = licdate,
                    ErrorTime = ErrorTime
                };
                if (errorcode == 0) errorcode = DateDiff(DateTime.Now, l.AuDate);
                string str = cryptHelper.Encrypt(JsonHelper.ToJson(o));
                Tuple<string, int,string> r = Tuple.Create(l.Company, errorcode, str); 
                return r; 
               
            }
            catch (Exception ex) {

                return Tuple.Create("错误:"+ex.Message,-999,"");
               
            }
        
        }
        public static void Reflash(string str)
        {
            string licPath = AppDomain.CurrentDomain.BaseDirectory + @"WinProLic.lic";
            System.IO.File.WriteAllText(licPath, str, Encoding.UTF8);
        }

        public static int DateDiff(DateTime dateStart, DateTime dateEnd)
        {
            DateTime start = Convert.ToDateTime(dateStart.ToShortDateString());
            DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString());
            TimeSpan sp = end.Subtract(start);
            return sp.Days;
        }
    }
    public class LicEntity{
     public   string Company { get; set; }
        public DateTime AuDate { get; set; }
        public string IsFirst { get; set; }
       public int LicDate { get; set; }
        public int ErrorTime { get; set; }
    }
}
